<?php
namespace Admin\Controller;
/**
* 文章管理
*/
use Think\Model;
class ContentController extends CommonController{

    /**
    * 文章管理
    */
    public function index(){
    	
        if(!$_REQUEST['group']){
            _apiReturn(0,'配置链接中必须带分组key');
        }
        $mCat = M('CatsGroup');
        $group = $mCat->where('group_key = "'.$_REQUEST['group'].'"')->find();
		         
        if(!$group){
            _apiReturn(0,"对不起，找不到对应的文章分组,无法进入编辑");
        }
        $data= CatController::getdata_cats($group['id']);
		
		
	
		$this->cats = $result;
        $this->display();
    }

    public function getdata(){
        
        $p = I('p') ? I('p') : 1;
        $row = I('row') ? I('row') : 10;
		$group=I('group');
		if(!$_REQUEST['group']){
            _apiReturn(0,'配置链接中必须带分组key');
        }
		
		$group_id = D('CatsGroup')->where('group_key="'.$group.'"')->getField('id');
		if(!$group_id )_apiReturn(0,"对不起，找不到对应的文章分组,无法加载数据");
        $m = D('Contents');
        if(I('condition')) {
            $condition = condition_to_array(I('condition')); //加入条件参数
            foreach($condition as $key=>$val){
                if($key == 'id' || $key == 'status'){
                    $map[$key] = $val;
                }else{
                    $map[$key] = array('like',"%{$val}%");
                }
            }
        }

        $sql = 'SELECT DISTINCT mini_contents.*,(SELECT GROUP_CONCAT(cat_name) FROM mini_content_cats JOIN mini_cats ON mini_content_cats.`cid` = mini_cats.`id` WHERE mini_content_cats.`content_id` = mini_contents.`id` 
                    AND mini_cats.`group_id` = "'.$group_id.'") AS cats FROM mini_contents JOIN mini_content_cats ON mini_contents.`id` = mini_content_cats.`content_id` WHERE 1=1';

        $sqlcount = 'SELECT COUNT(DISTINCT mini_contents.id) AS total FROM mini_contents JOIN mini_content_cats ON mini_contents.`id` = mini_content_cats.`content_id` WHERE 1=1';
        
        $query = '';

        foreach($map as $key=>$val){
            if(is_array($val)){
                $query .= ' AND mini_contents.`'.$key.'` '.$val[0].' "'.$val[1].'"';
            }else{
                $query .= ' AND mini_contents.`'.$key.'` = '.$val;
            }
        }

        if(I('cid')){
            $query .= ' AND mini_content_cats.`cid` = '.I('cid');
        }

        if(I('group')){
            $query .= ' AND mini_contents.`group` = "'.I('group').'"';
        }

        $sql .= $query;
        $sqlcount .= $query;
 		$sql .= ' order by create_time desc';  
        $sql .= ' limit '.($p-1)*$row.','.$row;        
        $data['data'] = $m->query($sql);
        if(count($data['data']) == 1){
            if($data['data'][0]['id'] == null){
                $data['data'] = array();
            }
        }
        
		/*foreach($data['data'] as $k=>$v){
			if($data['data'][$k]['label_ids']){
				$tmparr = explode(",",$data['data'][$k]['label_ids']);
				$str = "";
				
				foreach($tmparr as $v){
					if($v){
						$str.="【".$labelarr[$v]."】"; 
					}
				}
				$data['data'][$k]['tags'] = $str;
			}else{
				$data['data'][$k]['tags'] = "";
			}
		}*/
		
        $data['page']['total'] =  $m->query($sqlcount);
        $data['page']['total'] = $data['page']['total'][0]['total'];
		$data['page']['cur'] = $p;
		$data['page']['row'] = $row;
		
		_apiReturn(1, L('success'), $data,$sql); //数据获取成功
    }


    public function edit(){
        if($_REQUEST['group']){
            $info['group'] = $_REQUEST['group'];
        }
        $info['status'] = 1; //默认发布
        if($_GET['id']){
            $info = D('Contents')->relation(true)->find($_GET['id']);
			/*$info['cids'] = D('ContentCats')->where('content_id='.$_GET['id'])->getField('cid',true);*/
			$map['fk_id'] = $_GET['id'];
            $obj = D('ObjVideoRelation')->where($map)->relation(true)->find();
            $info['video'] = $obj['video'];
            if($obj['vframe']) $info['video']['vframe'] = $obj['vframe'];
			
        }
        if($info['group'] == ""){
            _apiReturn(0,"对不起，当前文章编辑没有设置分组,无法进入编辑");
        }
        $mCat = M('CatsGroup');
        $group = $mCat->where('group_key = "'.$info['group'].'"')->find();        
        if(!$group){
            _apiReturn(0,"对不起，找不到对应的文章分组,无法进入编辑");
        }
        $this->info = $info;
        $this->cats = CatController::getdata_cats($group['id']);
        $this->display();
    }
    
	public function get_c_e_data($id){
		
		if(!$id) _apiReturn(0, 'ID不能为空', $data, $url);
		$sql = 'SELECT A.*,B.`listorder` FROM mini_exam A JOIN mini_content_exams B ON A.`id`=B.`eid` WHERE B.`content_id`='.$id;
		$sql.=" order by B.`listorder` asc";
		$model = new Model();
		$result = $model->query($sql);
		return $result;
	}
    public function edit_post(){
    	
        if(IS_POST){
        	
            if($_POST['title'] == ""){
                _apiReturn(0,"标题不能为空");
            }
            if(count($_POST['cids']) == 0){
                _apiReturn(0,"请至少选择一个分类");
            }
           
          
            if($_POST['status'] == ""){
                $_POST['status'] = 0;
            }
            $m = D('Contents');
            $mImg = D('MaterialImages');
            $mFile = D('MaterialFiles');
            $mcc = M('ContentCats'); //文章分类要删除掉
            $videoLogic = D('MaterialVideos','Logic');
            $mVidoe = D('MaterialVideos');
		
            $data['title'] = $_POST['title'];
			$data['content'] = $_POST['content'];
			
			$data['keywords'] = $_POST['keywords'];
			$data['desc'] = $_POST['desc'];
			$data['update_time'] = Date('Y-m-d H:i:s');
			if($_POST['fengmian']){
				$data['fengmian'] = $_POST['fengmian'];
			}else{
				if($_POST['video']['id']){
					$videoUrl = $mVidoe->where('id='.$_POST['video']['id'])->getField('url');
					$data['fengmian'] = $videoUrl.'?vframe/jpg/offset/'.$_POST['video']['vframe'];
				}
			}
			if($_POST['imgids'][0]){
				$data['fengmian'] = $mImg->where('id='.$_POST['imgids'][0])->getField('url');
			}
			
			$data['source'] = $_POST['source'];
			$data['id'] = $_POST['id'];
			$data['group'] = $_POST['group'];
			$data['listorder'] = $_POST['listorder'];
			$data['status'] = $_POST['status'];
			
            if(!$data){
                _apiReturn(0,'$m->getError()');
            }
	
            if($data['id']){
                if($m->save($data)){
                
                	
                    //更新分类信息
                    $mcc->where('content_id = '.$data['id'])->delete(); //先删除原有关系
                    //添加现有关系
                    foreach($_POST['cids'] as $key=>$val){
                        $tmpData = array(
                            'content_id' => $data['id'],
                            'cid' => $key
                        );
                        $mcc->add($tmpData);
                    }
                    for($i = 0 ; $i < count($_POST['imgids']);$i++){
                        $tmpData = array(
                            'id' => $_POST['imgids'][$i],
                            'fk_id' => $data['id'],
                            'fk_group' => $_POST['group'],
                            'listorder' => $_POST['imglistorders'][$i],
                            'title' => $_POST['imgtitles'][$i],
                            'redurl' => $_POST['imgredurls'][$i],
                        );
                        $mImg->save($tmpData);
                    }
                    for($i = 0 ; $i < count($_POST['fileids']) ;$i++){
                        $tmpData = array(
                            'id' => $_POST['fileids'][$i],
                            'fk_id' => $data['id'],
                            'fk_group' => $_POST['group']
                        );
                        $mFile->save($tmpData);
                    }
                    $videoLogic->_save($data['id'],$data['group'],$_POST['video']); //更新视频

                    $this->success("文章编辑成功");
                }else{
                    $this->error("文章编辑失败");
                }
            }else{
            	if(!$_POST['author']){
					$data['author'] = $_SESSION['loginUser']['username'];
				}
				$data['uid'] = $_SESSION['loginUser']['uid'];
				
                $data['create_time'] = $data['update_time'];
                $data['id'] = $m->add($data);
                if($data['id']){
                
                	
                    //更新分类信息
                    $mcc->where('content_id = '.$data['id'])->delete(); //先删除原有关系
                    foreach($_POST['cids'] as $key=>$val){
                        $tmpData = array(
                            'content_id' => $data['id'],
                            'cid' => $key
                        );
                        $mcc->add($tmpData);
                    }
                    for($i = 0 ; $i < count($_POST['imgids']);$i++){
                        $tmpData = array(
                            'id' => $_POST['imgids'][$i],
                            'fk_id' => $data['id'],
                            'fk_group' => $_POST['group'],
                            'listorder' => $_POST['imglistorders'][$i],
                            'title' => $_POST['imgtitles'][$i],
                            'redurl' => $_POST['imgredurls'][$i],
                        );
                        $mImg->save($tmpData);
                    }
                    for($i = 0 ; $i < count($_POST['fileids']) ;$i++){
                        $tmpData = array(
                            'id' => $_POST['fileids'][$i],
                            'fk_id' => $data['id'],
                            'fk_group' => $_POST['group']
                        );
                        $mFile->save($tmpData);
                    }
                    $videoLogic->_save($data['id'],$data['group'],$_POST['video']); //更新视频
                    $this->success("文章添加成功");
                }else{
                    $this->error("文章添加失败");
                }
            }
            
        }
    }
    
    public function del(){
        $this->_del(D('Contents'),I('ids'));
    }
	
	
	public function recom_index(){
		$this->display();
	}
	public function get_recommend_data(){
		$m= D('Contents');
		$p = I('p')?I('p'):1;
		$row = I('row')?I("row"):10;
		$step = I('step');
		$gtype = I('type');
		$keyword = I('keyword');
		$yjcats = D('Cats')->where('group_id=3')->getField('id',true);
		if($step){
			$mapp['cid'] = $step;
		}else{
			$mapp['cid'] = array('in',$yjcats);
		}
		
		
		
		$n = D('ContentCats');
		$temp = $n->where($mapp)->getField('content_id',true);
		$map['id'] = array('in',$temp); 
		$labelarr =  D("Cats")->where('group_id=2')->getField('id,cat_name');
		if($keyword){
		
			if($gtype == 'id'){
					if(in_array($keyword,$temp)){
						$map['id'] = $keyword;	
					}else{
						$map['id'] = -1;
					}
					
			
				
			}
			if($gtype == 'title'){
				$map['title'] = array('like',"%".$keyword."%");
			}
			if($gtype == 'author'){
				
				$map['author'] = array('like',"%".$keyword."%");
			}
		}
		
		
		
		$map['status'] = 1;
		
		$data['data'] = $m->where($map)->limit(($p-1)*$row,$row)->order('listorder desc,update_time desc')->select();
		foreach($data['data'] as $k=>$v){
			if($data['data'][$k]['label_ids']){
				$tmparr = explode(",",$data['data'][$k]['label_ids']);
				$str = "";
				
				foreach($tmparr as $v){
					if($v){
						$str.="【".$labelarr[$v]."】"; 
					}
				}
				$data['data'][$k]['tags'] = $str;
			}else{
				$data['data'][$k]['tags'] = "";
			}
		}
		
		$count = $m->where($map)->count();
		$data['page']['total'] = $count;
		$data['page']['cur'] = $p;
		$data['page']['row'] = $row;
		_apiReturn(1, L('success'), $data, $url);
	}
	
	
	
	public function get_hudong_data(){
		$m= D('Contents');
		$p = I('p')?I('p'):1;
		$row = I('row')?I("row"):10;
		$level = I('level');
		$gtype = I('type');
		$keyword = I('keyword');
	
		$mapd['cat_name'] = '互动中心';
		$hcamid = M('Cats')->where($mapd)->getField('id');
		$ids =D('ContentCats')->where('cid='.$hcamid)->getField('content_id',true);
		$map['id']=array('in',$ids);
		if($level){
			$map['level'] = $level;
		}
	
		if($keyword){
			if($gtype == 'id'){
				if(in_array($keyword,$ids)){
						$map['id'] = $keyword;	
					}else{
						$map['id'] = -1;
					}
			}
			if($gtype == 'title'){
				$map['title'] = array('like',"%".$keyword."%");
			}
			if($gtype == 'author'){
				$map['author'] = array('like',"%".$keyword."%");
			}
			if($gtype == 'status'){
				if($keyword == '发布'){
					$map['status'] = 1;
				}
				if($keyword == '关闭'){
					$map['status'] = 0;
				}
					
				
			}
			if($gtype == 'label'){
					$map['label_ids'] = array('like',"%,".$keyword.",%");						
			}
			
			if($gtype == 'sid'){
				
				$map['sid'] = $keyword;
			}
			if($gtype == 'time'){
				$timedata=explode('|',$keyword);
				if($timedata[0]){
					
					if($timedata[1]){
						$map['create_time']  = array('between',array($timedata[0],$timedata[1]));
					}else{
						$map['create_time']=array('gt',$timedata[0]);
					}
				}else{
					if($timedata[1]){
						$map['create_time']=array('lt',$timedata[1]);
					}
				}
				
				
			}
			/*if($gtype == 'label'){
				$id = array_keys($labelarr,$keyword);
				if($id){
					$map['label_ids'] = array('like',"%,".$id[0].",%");
				}
				
			}*/
		}
		
		$data['data'] = $m->where($map)->limit(($p-1)*$row,$row)->order('create_time desc')->select();
		
		
		$count = $m->where($map)->count();
		$data['page']['total'] = $count;
		$data['page']['cur'] = $p;
		$data['page']['row'] = $row;
		_apiReturn(1, L('success'), $data, $url);
	} 



}